package com.zsw.upload;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerHandler extends ChannelInboundHandlerAdapter{
	
	private final static Logger LOG = LoggerFactory.getLogger(ServerHandler.class);
	
	private boolean first = true;
    private FileOutputStream fos;
    private BufferedOutputStream bufferedOutputStream;
    private BufferedReader bufferedReader;
 
    /*
     * channelAction
	 * channel 通道
	 * action  活跃的
	 * 当客户端主动链接服务端的链接后，这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
	 *
	 */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        first = true;
        LOG.debug(ctx.channel().localAddress().toString() + " channelActive");
    }
 
    /*
     * channelInactive
     * channel 	通道
     * Inactive 不活跃的
     * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	LOG.debug(ctx.channel().localAddress().toString() + " channelInactive");
        // 关闭流
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
        bufferedReader.close();
        first = false;
    }
 
    /*
     * channelRead
     * channel 通道
     * Read    读
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] bytes = new byte[buf.readableBytes()];
		buf.readBytes(bytes);
        if (first) {
        	bufferedReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
        	String str = bufferedReader.readLine();
        	LOG.debug(str);
            first = false;
            File file = new File("F://test" + new SimpleDateFormat("yyyymmddhhmmss").format(new Date()) + ".zip");
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                fos = new FileOutputStream(file);
                bufferedOutputStream = new BufferedOutputStream(fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return;
        }
        LOG.debug("本次接收内容长度：" + msg.toString().length());
        try {
            bufferedOutputStream.write(bytes, 0, bytes.length);
            buf.release();
        } catch (IOException e) {
            e.printStackTrace();
        }
//		writeInt(ctx,0);
    }
 
    /*
     * channelReadComplete
     * channel  通道
     * Read     读取
     * Complete 完成
     * 在通道读取完成后会在这个方法里通知，对应可以做刷新操作
     * ctx.flush()
     */
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    	LOG.debug("通道读取完成");
        ctx.flush();
    }
 
    /*
     * exceptionCaught
     * exception	异常
     * Caught		抓住
     * 抓住异常，当发生异常的时候，可以做一些相应的处理，比如打印日志、关闭链接
     */
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.close();
        LOG.debug("异常信息：\r\n" + cause.getMessage());
    }
    
	public void writeInt(ChannelHandlerContext ctx,Integer a) {
		ctx.write(new byte[] {  
				(byte) (a & 0xFF),  
				(byte) ((a >> 8) & 0xFF),     
				(byte) ((a >> 16) & 0xFF),     
		        (byte) ((a >> 24) & 0xFF)
		    });
		ctx.flush();
	}
}
